package com.inspector.app.ui.flight.statusBar

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Typeface
import android.location.Location
import android.os.BatteryManager
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import com.inspector.app.di.location.gnss.GnssStatusInstance
import com.inspector.app.di.util.geomagnetism.GeomagnetismUtils
import com.inspector.app.di.vo.LocationPosition
import com.inspector.app.util.CommonUtil
import com.mapsforge.utils.TopoUtils
import java.text.SimpleDateFormat
import java.util.Date
import java.util.TimeZone
import java.util.concurrent.TimeUnit

/**
 * 飞行状态栏工具类
 */
object FlightStatusBarUtils {


    @SuppressLint("SimpleDateFormat")
    private val format = SimpleDateFormat("HH:mm:ss")
    fun formatBJTime(flightStatusBar: FlightStatusBar) {
        flightStatusBar.content = format.format(Date())
    }

    fun formatHX(flightStatusBar: FlightStatusBar, mLastKnownLocation: Location?) {
        if (mLastKnownLocation == null) {
            flightStatusBar.resetValues()
            return
        }
        flightStatusBar.content =
            CommonUtil.formatDouble(mLastKnownLocation.bearing.toDouble(), 1) + "°"
        flightStatusBar.extendContent = ""
    }

    //[海拔高度]
    fun formatAltitude(flightStatusBar: FlightStatusBar, mLastKnownLocation: Location?) {
        if (mLastKnownLocation == null) {
            flightStatusBar.resetValues()
            return
        }
        flightStatusBar.content = CommonUtil.formatDouble(mLastKnownLocation.altitude, 1)
        flightStatusBar.extendContent = "m"
    }

    /**
     * 计算速度
     * 默认使用GPS速度, 若GPS速度不可用, 则通过球面距离求速度、
     * 速度单位, 统一标准
     *
     * 目前取的第一个点和最后一个点,关于点有效性检测 待方案优化
     * 比如检测 1.点距离间隔 2.时间间隔
     */
    fun formatSpeed(flightStatusBar: FlightStatusBar, mLastKnownLocation: Location?) {
        if (mLastKnownLocation == null) {
            flightStatusBar.resetValues()
            return
        }
        flightStatusBar.content = CommonUtil.speedConversion(mLastKnownLocation.speed.toDouble())
        flightStatusBar.extendContent = CommonUtil.getSpeedUnit()
    }

    /**
     * 获取速度 米每秒
     *
     */
    fun getSpeed(firstLocPoint: LocationPosition, lastLocPoint: LocationPosition): Double {
        try {
            // [2024/1/16 速度急剧变化的情况]
            val second =
                TimeUnit.NANOSECONDS.toMillis(lastLocPoint.nanoTime - firstLocPoint.nanoTime) / 1000.0
            if (second == 0.0) {
                return lastLocPoint.currentSpeed.toDouble()
            }

            //[GPS速度不可用情况下]
            if (!lastLocPoint.isSpeedEnabled) {
                val distance =
                    TopoUtils.distance(lastLocPoint.latLngPoint, firstLocPoint.latLngPoint)
                return distance / second
            }

            //[GPS速度为0的情况]
            if (lastLocPoint.currentSpeed == 0f) {
                return 0.0
            }

            val distance = TopoUtils.distance(lastLocPoint.latLngPoint, firstLocPoint.latLngPoint)
            val speed = distance / second
            if (lastLocPoint.speedAccuracyMetersPerSecond == 0f) {
                return speed
            }

            //[速度在范围内, 则正常返回]
            val start = (lastLocPoint.currentSpeed - lastLocPoint.speedAccuracyMetersPerSecond)
            val end = (lastLocPoint.currentSpeed + lastLocPoint.speedAccuracyMetersPerSecond)
            if (speed in start..end) {
                return speed
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return lastLocPoint.currentSpeed.toDouble()
    }


    //[当前经纬度]
    fun formatDQJWD(flightStatusBar: FlightStatusBar, mLastKnownLocation: Location?) {
        if (mLastKnownLocation == null) {
            flightStatusBar.resetValues()
            return
        }
        val formatLng = "E " + CommonUtil.getFormatLatLng(mLastKnownLocation.longitude, "")
        val formatLat = "N " + CommonUtil.getFormatLatLng(mLastKnownLocation.latitude, "")
        flightStatusBar.content = formatLng
        flightStatusBar.extendContent = formatLat
    }

    fun formatDQJWDSpan(content: String, extendContent: String): SpannableString {
        val totalContent = content + "\n" + extendContent
        val string = SpannableString(totalContent)
        string.setSpan(StyleSpan(Typeface.NORMAL), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        string.setSpan(ForegroundColorSpan(Color.parseColor("#A5A8AC")), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        string.setSpan(StyleSpan(Typeface.BOLD), 1, (content + "\n").length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        string.setSpan(StyleSpan(Typeface.NORMAL), (content + "\n").length, (content + "\n").length + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        string.setSpan(ForegroundColorSpan(Color.parseColor("#A5A8AC")), (content + "\n").length, (content + "\n").length + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        string.setSpan(StyleSpan(Typeface.BOLD), (content + "\n").length + 1, totalContent.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        return string
    }

    /**
     * 计算磁差
     */
    fun formatMagneticDif(flightStatusBar: FlightStatusBar, mLastKnownLocation: Location?) {
        if (mLastKnownLocation == null) {
            flightStatusBar.resetValues()
            return
        }

        val magneticDif = GeomagnetismUtils.instance.getGeomagnetismByPoint(
            mLastKnownLocation.longitude, mLastKnownLocation.latitude
        )
        flightStatusBar.content = CommonUtil.formatDouble(magneticDif, 1) + "°"
        flightStatusBar.extendContent = ""
    }

    fun formatDL(flightStatusBar: FlightStatusBar, batteryManager: BatteryManager?) {
        val electricity =
            batteryManager?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) ?: 0
        flightStatusBar.content = electricity.toString()
        flightStatusBar.extendContent = "%"
    }

    @SuppressLint("SimpleDateFormat")
    fun formatUTC(flightStatusBar: FlightStatusBar) {
        val format = SimpleDateFormat("HH:mm:ss")
        format.timeZone = TimeZone.getTimeZone("UTC")
        flightStatusBar.content = format.format(Date())
    }

    fun formatWXS(flightStatusBar: FlightStatusBar) {
        val satelliteArray: IntArray = GnssStatusInstance.getInstance().satelliteArr
        flightStatusBar.content = satelliteArray[0].toString()
        flightStatusBar.extendContent = satelliteArray[1].toString()
    }

    fun formatWXSSpan(availableCount: String, totalCount: String): SpannableString {
        val content = "$availableCount($totalCount)"
        val mSpannableString = SpannableString(content)
        mSpannableString.setSpan(StyleSpan(Typeface.BOLD), 0, content.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        mSpannableString.setSpan(
            ForegroundColorSpan(Color.GREEN), 0, availableCount.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        mSpannableString.setSpan(ForegroundColorSpan(Color.WHITE), totalCount.length, content.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        return mSpannableString
    }


    fun formatMagneticHeading(flightStatusBar: FlightStatusBar, mLastKnownLocation: Location?) {
        try {
            if (mLastKnownLocation == null) {
                flightStatusBar.resetValues()
                return
            }

            val magneticDif = GeomagnetismUtils.instance.getGeomagnetismByPoint(
                mLastKnownLocation.longitude, mLastKnownLocation.latitude)
            val angle = mLastKnownLocation.bearing.toDouble()
            val tempMagneticHeading: Double = angle - magneticDif

            if (tempMagneticHeading >= 360) {
                if (tempMagneticHeading == 360.0) {
                    flightStatusBar.content = "0°"
                    flightStatusBar.extendContent = ""
                    return
                }
                flightStatusBar.content = CommonUtil.formatDouble(tempMagneticHeading - 360, 1) + "°"
                flightStatusBar.extendContent = ""
                return
            }
            flightStatusBar.content = CommonUtil.formatDouble(tempMagneticHeading, 1) + "°"
            flightStatusBar.extendContent = ""
        } catch (e: NumberFormatException) {
            e.printStackTrace()
        }
    }

}